from flask import Flask
import os
from flask_cors import CORS
from flask_sqlalchemy import SQLAlchemy
from RealProject.settings import BASE_DIR
from flask_migrate import Migrate
from RealProject.db_init import session,db,migrate
from app.user.views import bp as user_bp
from app.user.models import db as user_db
from app.datafactory.views import datafactory_bp
from app.datafactory.models import Project as project_db
import pymysql


def create_app():
    app = Flask(__name__)

    # 连接数据库连接url
    app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://root:root@127.0.0.1:3306/flaskstudy'
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
    # 查询时会显示原始SQL语句
    app.config["SQLALCHEMY_ECHO"] = False


    # 把SQLAlchemy组件注册到项目中

    db.init_app(app)
    migrate.init_app(app, db)
    #解决跨域
    # CORS(app, supports_credentials=True)
    # @app.after_request
    # def after_request(response):
    #     # response.headers.add('Access-Control-Allow-Origin',  '*')
    #     response.headers.add('Access-Control-Allow-Headers', 'Content-Type,Authorization')
    #     # response.headers.add('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS')
    #     response.headers.add('Access-Control-Allow-Credentials', 'true')
    #     return response
    with app.app_context():
        from app.datafactory import models
        from app.user import models
        from app.blog import models
        db.create_all()

        app.register_blueprint(user_bp)
        app.register_blueprint(datafactory_bp)

    return app